using Microsoft.EntityFrameworkCore;

class App
{
    public static WebApplication CreateApp(WebApplicationBuilder webApplicationBuilder)
    {
        var webApplication = webApplicationBuilder.Build();

        webApplication.MapGet("/", () => "Hello World!");

        webApplication.MapGet("/todoitems", async (TodoDb db) =>
            await db.Todos.ToListAsync());

        webApplication.MapGet("/todoitems/complete", async (TodoDb db) =>
            await db.Todos.Where(t => t.IsComplete).ToListAsync());

        webApplication.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
            await db.Todos.FindAsync(id)
                is Todo todo
                ? Results.Ok(todo)
                : Results.NotFound());

        webApplication.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
        {
            db.Todos.Add(todo);
            await db.SaveChangesAsync();

            return Results.Created($"/todoitems/{todo.Id}", todo);
        });

        webApplication.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
        {
            var todo = await db.Todos.FindAsync(id);

            if (todo is null) return Results.NotFound();

            todo.Name = inputTodo.Name;
            todo.IsComplete = inputTodo.IsComplete;

            await db.SaveChangesAsync();

            return Results.NoContent();
        });

        webApplication.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
        {
            if (await db.Todos.FindAsync(id) is Todo todo)
            {
                db.Todos.Remove(todo);
                await db.SaveChangesAsync();
                return Results.Ok(todo);
            }

            return Results.NotFound();
        });

        return webApplication;
    }
}